function ToggleAppAndH5(AppUrl, AppCallback = () => {}) {
  // 先走APP
  const ifr = document.createElement("iframe");
  ifr.className = "iframe";
  ifr.src = AppUrl;
  ifr.style.display = "none";
  document.body.appendChild(ifr);

  // 800毫秒后调用H5链接
  let timer = setTimeout(function () {
    clearTimeout(timer);
    AppCallback();
  }, 800);

  window.onblur = function () {
    clearInterval(timer);
  };
}

function Callback(mapType, params) {
  // 这里放相关H5链接
  if (mapType === "baidu") {
    console.log(document.getElementsByClassName("iframe"), "sss");
    document
      .getElementsByClassName("iframe")[0]
      .setAttribute(
        "src",
        "http://api.map.baidu.com/direction?origin=latlng:" +
          params.curLat +
          "," +
          params.curLng +
          "|name:" +
          params.currAddr +
          "&destination=latlng:" +
          params.elat +
          "," +
          params.elng +
          "|name:" +
          params.eaddr +
          "&region=" +
          params.cityName +
          "&mode=driving&output=html&src=http://172.16.3.121:8081/openMap"
      );
  } else if (mapType === "amap") {
    document
      .getElementsByClassName("iframe")[0]
      .setAttribute(
        "src",
        "https://ditu.amap.com/dir?type=car&from[lnglat]=" +
          params.curLng +
          "," +
          params.curLat +
          "&from[name]=" +
          params.currAddr +
          "&to[lnglat]=" +
          params.elng +
          "," +
          params.elat +
          "&to[name]=" +
          params.eaddr +
          "&src=com.youbei.chefu"
      );
  }
}

const u = navigator.userAgent;
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

export function openGaoDeiMap(params) {
  // 苹果和安卓头部不一样
  let proto = isiOS ? "iosamap://path" : "amapuri://route/plan";

  const AppUrl =
    proto +
    "?t= 0&slat=" +
    params.curLat +
    "&slon=" +
    params.curLng +
    "&sname=" +
    params.currAddr +
    "&dlat=" +
    params.elat +
    "&dlon=" +
    params.elng +
    "&dname=" +
    params.eaddr +
    "&src=xxx";

  ToggleAppAndH5(AppUrl, Callback.bind(null, "amap", params));
}

export function openBaiDuMap(params) {
  // 苹果和安卓头部不一样
  let proto = isiOS ? "baidumap://" : "bdapp://";

  const AppUrl =
    proto +
    "map/direction?region=" +
    params.cityName +
    "&origin=latlng:" +
    params.curLat +
    "," +
    params.curLng +
    "|name:" +
    params.currAddr +
    "&destination=latlng:" +
    params.elat +
    "," +
    params.elng +
    "|name:" +
    params.eaddr +
    "&coord_type=bd09ll&mode=driving&src=com.youbei.chefu";

  ToggleAppAndH5(AppUrl, Callback.bind(null, "baidu", params));
}
